package com.xudow.app.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.activeshare.edu.ucenter.models.base.SysSchool;
import com.xudow.app.R;
import com.xudow.app.ui.task.SysSchoolsTask;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 公办学校选择Activity
 *
 * @author lukecheng
 */
public class SysSchoolActivity extends BaseActivity implements AdapterView.OnItemClickListener {

    /**
     * TODO:添加学校搜索
     */

    private ListView schoolListview;

    private List<SysSchool> schools;
    private List<String> schoolNames;
    private ArrayAdapter<String> schoolAdapter;

    private SysSchoolsTask sysSchoolsTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sys_school);

        schoolListview = (ListView) findViewById(R.id.schools);
        schoolListview.setOnItemClickListener(this);

        showLodingDialog(getString(R.string.loading));

        sysSchoolsTask = new SysSchoolsTask(this, sysSchoolsTaskHandler);
        addTask(sysSchoolsTask);
        sysSchoolsTask.execute();
    }

    public void onBackBtnClick(View view) {
        finish();
    }

    private Handler sysSchoolsTaskHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideLoadingDialog();

            if (SysSchoolsTask.SUCCESS == msg.what) {
                SysSchool[] schoolArr = (SysSchool[]) msg.getData().get("schools");

                schools = new ArrayList<SysSchool>();
                schoolNames = new ArrayList<String>();

                schools.addAll(Arrays.asList(schoolArr));

                for (SysSchool ss : schools) {
                    schoolNames.add(ss.getName());
                }

                schoolAdapter = new ArrayAdapter<String>(SysSchoolActivity.this, R.layout.item_subject_list, schoolNames);
                schoolListview.setAdapter(schoolAdapter);
                schoolAdapter.notifyDataSetChanged();
            } else {
                String message = getString(R.string.loading_fail);
                Toast.makeText(SysSchoolActivity.this, message, Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent();
        intent.putExtra("schoolId", schools.get(position).getId());
        intent.putExtra("schoolName", schools.get(position).getName());

        setResult(RESULT_OK, intent);
        finish();
    }
}
